package com.tony.lock;

import javax.swing.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author tonywang
 * @date 8/6/2018
 */
public class Cache {
    static Map<String, Object> map = new HashMap<String, Object>();
    static ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
    static Lock r = rwl.readLock();
    static Lock w = rwl.writeLock();
    static CountDownLatch countDownLatch = new CountDownLatch(11);

    // 获取一个key对应的value
    public static final Object get(String key) {
        r.lock();
        try {
            return map.get(key);
        } finally {
            r.unlock();
        }
    }

    // 设置key对应的value，并返回旧的value
    public static final Object put(String key, Object value) {
        w.lock();
        try {
            return map.put(key, value);
        } finally {
            w.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        for(int i=0;i<=10;i++) {
            Thread thread = new Thread(new Locks(i));
            thread.start();
        }
//        for(int i=0;i<=11;i++) {
//            countDownLatch.countDown();
//        }
        System.out.println(Cache.map);
    }

    static class Locks implements Runnable {
        int seed;
        Locks(int seed){
            this.seed = seed;
        }
        @Override
        public void run() {
//            try {
//                countDownLatch.await();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            for (int i=0;i<5;i++) {
                Cache.putAndGet(i+"s",i + seed);
            }
        }
    }

    //在同一线程中读写锁不互斥
    public static  final  Object putAndGet(String key, Object value) {
        r.lock();
        try {
            w.lock();
            if (map.get(key) != null) {
                return map.get(key);
            }
            map.put(key,value);
        } finally {
            r.unlock();
            w.unlock();
        }
        return map.get(key);
    }
    // 清空所有的内容
    public static final void clear() {
        w.lock();
        try {
            map.clear();
        } finally {
            w.unlock();
        }
    }
}
